package com.rabbit.videoplayer.widget

import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import com.rabbit.videoplayer.listener.OnVideoStatusListener
import com.rabbit.videoplayer.R
import com.rabbit.videoplayer.listener.OnCastScreenListener
import com.rabbit.videoplayer.tools.TimeFormater

class CastScreenView(context: Context, attrs: AttributeSet?=null): ConstraintLayout(context, attrs), OnVideoStatusListener {


    private val btnBack: View
    private val btnPlay: View
    private val btnClose: View
    private val seekBar: SeekBar
    private val ivPlay: ImageView
    private val tvDuration: TextView
    private val tvDeviceName: TextView
    private val tvConnectError: TextView
    private val tvCurrentPosition: TextView
    private val layoutConnecting: View


    // 当前是否正在触摸进度条
    private var isSeekBarOnTouch = false
    private var onCastScreenListener: OnCastScreenListener? = null

    init {
        LayoutInflater.from(context).inflate(R.layout.view_wb_mix_cast_screen, this, true)
        setBackgroundColor(Color.BLACK)
        btnPlay = findViewById(R.id.layout_video_play)
        btnBack = findViewById(R.id.layout_cast_screen_back)
        btnClose = findViewById(R.id.layout_close_cast_screen)
        seekBar = findViewById(R.id.sb_video_bottom)
        ivPlay = findViewById(R.id.iv_video_play)
        tvDuration = findViewById(R.id.tv_video_duration)
        tvDeviceName = findViewById(R.id.tv_device_name)
        tvConnectError = findViewById(R.id.tv_error_cast_screen)
        tvCurrentPosition = findViewById(R.id.tv_video_current_position)
        layoutConnecting = findViewById(R.id.layout_connecting)

        // 默认隐藏
        hide()

        bindEvent()
    }

    private fun bindEvent(){
        btnBack.setOnClickListener {
            if (context is Activity) {
                (context as Activity).finish()
            }
        }

        btnClose.setOnClickListener {
            closeCastScreen()
        }

        btnPlay.setOnClickListener {
            if (!isDeviceConnected) return@setOnClickListener
            val isPlaying = onCastScreenListener?.onCastScreenPlay()?:false
            switchPlayOrPauseUI(isPlaying)
        }

        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {

            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    // 修改当前进度文本
                    val realProgress = progress * 1000L
                    updateCurrentPosition(realProgress, true)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                isSeekBarOnTouch = true
                onCastScreenListener?.isStartTrackingTouch(true)
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                isSeekBarOnTouch = false
                onCastScreenListener?.isStartTrackingTouch(false)
                // 返回告诉播放器当前的进度
                // 修改当前进度文本
                val realProgress = (seekBar?.progress ?: 0) * 1000L
                onCastScreenListener?.seekTo(realProgress)
            }
        })
    }

    fun isShowing(): Boolean {
        return visibility == View.VISIBLE
    }

    // 切换播放状态对应的UI
     fun switchPlayOrPauseUI(isPlaying: Boolean) {
        val drawableResId = if (isPlaying) {
            R.drawable.ic_wb_mix_video_pause
        } else {
            R.drawable.ic_wb_mix_video_play
        }
        ivPlay.setBackgroundResource(drawableResId)
    }

    private fun hide(){
        if (this.visibility != View.GONE) {
            this.visibility = View.GONE
        }
    }

    fun setCastScreenListener(listener: OnCastScreenListener){
        onCastScreenListener = listener
    }


    fun updateCurrentPosition(currentPosition: Long, fromUser: Boolean = false){
        tvCurrentPosition.text = TimeFormater.formatMs(currentPosition)
        if (!fromUser) {
            seekBar.progress = (currentPosition / 1000).toInt()
        }
    }

    fun closeCastScreen() {
        hide()
        isDeviceConnected = false
        onCastScreenListener?.onCloseCastScreen()
    }

    fun showCastScreen(deviceName: String, duration: Long){
        tvConnectError.text = ""
        tvConnectError.visibility = View.GONE
        tvDeviceName.text = deviceName
        seekBar.progress = 0
        seekBar.max = (duration / 1000).toInt()

        tvDuration.text =  TimeFormater.formatMs(duration)
        tvCurrentPosition.text =  TimeFormater.formatMs(0)

        layoutConnecting.visibility = View.VISIBLE

        isDeviceConnected = false
        show()
    }

    private var isDeviceConnected = false
    fun showConnected(){
        isDeviceConnected = true
        layoutConnecting.visibility = View.GONE
    }

    fun showDisConnect(msg: String){
        layoutConnecting.visibility = View.GONE
        tvConnectError.visibility = View.VISIBLE
        tvConnectError.text = msg
    }


    fun show(){
        if (this.visibility != View.VISIBLE) {
            this.visibility = View.VISIBLE
        }
    }


    override fun onVodInit(vararg init: Any?): Boolean {
        closeCastScreen()
        hide()
        return false
    }

    override fun onVodPrepared(vararg prepared: Any) {
        hide()
    }

    override fun onVodStart() {
        hide()
    }

    override fun onVodFirstFrameStart() {
        hide()
    }

    override fun onVodSwitchDisplayControlView() {
        
    }

    override fun onVodPause() {
        
    }

    override fun onVodStop() {
        hide()
    }

    override fun onVodError(vararg params: Any) {
    }
    override fun onVodComplete() {
    }

    override fun onVodRelease() {

    }

    override fun onVodLockedScreen(vararg params: Any) {
        
    }

    override fun onVodFullScreen(vararg params: Any) {

    }

    override fun onVodLoadingBegin() {
    }

    override fun onVodLoadingProgress(vararg params: Any) {

    }

    override fun onVodLoadingEnd() {
    }

    override fun onVodBackPress(): Boolean {
        return false
    }

    override fun onEpisodeSelected(){
    }

    override fun onVodShowUnlockUI(isDisplayUI: Boolean) {

    }

    override fun onVodSkits() {

    }
}